package com.itHaipeng.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//定义一套规则，被其他servlet继承，实现请求值分发到指定的方法
public class SelfServlet extends HttpServlet {
    //重写service，
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求路径
        StringBuffer requestURL = req.getRequestURL();
        int index=requestURL.lastIndexOf("/");
        String methodName = requestURL.substring(index+1);
        System.out.println(methodName);
        //获取最后一段路径
        //获取BrandServlet中的字节码对象
        Class<? extends SelfServlet> aClass = this.getClass();
        try {
            Method method = aClass.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
            //执行方法
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        //获取方法
    }
}
